package com.java.cloud.consumer.service.impl;

import com.java.cloud.bookstore.commons.util.JsonResult;
import com.java.cloud.consumer.service.Consumer8001Service;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@Service
public class Consumer8001ServiceImpl implements Consumer8001Service {

    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private RestTemplate restTemplate;

    private Integer index=0;

    @Override
    public JsonResult a() {
        //获取到所有的demo(服务的提供者)实例
        List<ServiceInstance> list=discoveryClient.getInstances("demo");
        //得到http://localhost:8011
        //轮询方案
       String uri= list.get(index).getUri()+"/demo";
      JsonResult result= restTemplate.getForObject(uri,JsonResult.class);
      if(index<list.size()-1){
          index++;
      }else{
          index=0;
      }
        return result;
    }

    @Override
    public JsonResult b(String name) {
        //获取到所有的demo(服务的提供者)实例
        List<ServiceInstance> list=discoveryClient.getInstances("demo");
        //得到http://localhost:8011
        //随机方式
        int random=(int) (Math.random()*list.size());
        String uri= list.get(random).getUri()+"/demo/"+name;
        JsonResult result= restTemplate.getForObject(uri,JsonResult.class);
        return result;
    }

    @Override
    public JsonResult c() {
        return restTemplate.getForObject("http://demo/demo",JsonResult.class);
    }

    @Override
    public JsonResult d(String name) {
        return restTemplate.getForObject("http://demo/demo"+name,JsonResult.class);
    }
    @Override
    public JsonResult c1(){
        return restTemplate.getForObject("http://demo/demo/c",JsonResult.class);
    }
    @Override
    public JsonResult d1(){
        return restTemplate.getForObject("http://demo/demo/d",JsonResult.class);
    }
    @Override
    public JsonResult e1(){
        return restTemplate.getForObject("http://demo/demo/e",JsonResult.class);
    }


}
